<template>
  <div class="panel-header">
    <div class="panel-title">
      <i class="panel-icon efficiency-icon"></i>
      <span>操作员效率分析</span>
    </div>
  </div>
  <div class="panel-body">
    <div ref="chartRef" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
const chart = ref(null)

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return

  chart.value = echarts.init(chartRef.value)

  // 设置图表响应式
  const resizeHandler = () => {
    chart.value && chart.value.resize()
  }
  window.addEventListener('resize', resizeHandler)

  // 组件卸载时移除事件监听
  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler)
    chart.value && chart.value.dispose()
  })

  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chart.value) return

  // 生成模拟数据
  const operatorData = []
  const operators = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']

  operators.forEach(operator => {
    // 随机生成产量和速度
    const production = Math.round(Math.random() * 4000 + 1000)
    const speed = Math.round(Math.random() * 20 + 10)

    operatorData.push({
      name: operator,
      value: [speed, production, Math.round(Math.random() * 10)]
    })
  })

  // 模拟数据
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return `${params.data.name}<br/>平均速度: ${params.data.value[0]} 米/分钟<br/>总产量: ${params.data.value[1]} 米`
      }
    },
    grid: {
      left: '10%',
      right: '5%',
      bottom: '10%',
      top: '10%'
    },
    xAxis: {
      type: 'value',
      name: '平均速度(米/分钟)',
      nameLocation: 'middle',
      nameGap: 30
    },
    yAxis: {
      type: 'value',
      name: '总产量(米)',
      nameLocation: 'middle',
      nameGap: 30
    },
    series: [
      {
        name: '操作员效率',
        type: 'scatter',
        symbolSize: function(data) {
          return data[2] * 4 + 15
        },
        emphasis: {
          focus: 'series',
          label: {
            show: true,
            formatter: function(param) {
              return param.data.name
            },
            position: 'top'
          }
        },
        itemStyle: {
          color: function(params) {
            // 根据速度设置不同的颜色
            const speed = params.data.value[0]
            if (speed > 25) return '#67C23A'
            if (speed > 15) return '#409EFF'
            return '#E6A23C'
          }
        },
        data: operatorData
      }
    ]
  }

  chart.value.setOption(option)
}

onMounted(() => {
  initChart()
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
